const fs = require('fs');
const path = require('path');
const execShPromise = require('exec-sh').promise;

const generateTagVersion = async () => {
  const crypto = require('crypto');
  const hash = crypto.createHash('md5');
  // 根据时间戳生成唯一hash
  hash.update(Date.now().toString());

  const version = hash.digest('hex').slice(0, 8);
  return version;
};

const TAGS = {
  prod: 'production',
  dev: 'dev',
};
const publish = async (tag = 'dev', pkgJson, cwd) => {
  if (tag === TAGS.production) {
    return execShPromise(`npm publish`);
  }
  const newVersion = await generateTagVersion();

  const newPkgJson = {
    ...pkgJson,
    version: `${pkgJson.version}-${tag}.${newVersion}`,
  };
  // 更改version
  fs.writeFileSync(path.resolve(cwd, './package.json'), JSON.stringify(newPkgJson, null, 2));

  return execShPromise(`npm publish --tag=${tag}`);
};

exports.publish = publish;
